const app = getApp()
var util = require('../../utils/util.js');
var util2 = require('../../utils/util2.js');

//将location信息添加入数据库
function addLocation() {
  wx.cloud
    .callFunction({
      name: "getopenid",
    })
    .then((res) => {
      let openid = res.result.openid;
      util2.getUserLocation()
      var location = wx.getStorageSync('location')
      //将location信息添加数据库
      wx.cloud
        .database()
        .collection("userInfo")
        .where({
          openid: openid
        })
        .update({
          data: {
            location: location
          }
        })
        .then((res) => {
          console.log("添加location信息成功", res);
        })
        .catch((res) => {
          console.log("添加location信息失败", res);
        });
    })
    .catch((res) => {
      console.log("获取openid失败", res);
    });

}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    theday: "",
    day: "1",
  },
  //获取用户的openid
  getOpenid() {
    wx.cloud
      .callFunction({
        name: "getopenid",
      })
      .then((res) => {
        let openid = res.result.openid;
        this.setData({
          openid: openid,
        });
        console.log("获取openid成功", openid);
        //this.sendAll(openid)
        // this.getUserProfile();
        this.getDBInfo(openid);
      })
      .catch((res) => {
        console.log("获取openid失败", res);
      });
  },
  getUserProfile() {
    // 调用函数必须绑定按钮
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: "展示用户信息", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
        });
      },
    });
  },
  addInfo() {
    wx.cloud
      .database()
      .collection("userInfo")
      .add({
        data: {
          openid: this.data.openid,
          avatarUrl: this.data.userInfo.avatarUrl,
          city: this.data.userInfo.city,
          country: this.data.userInfo.country,
          gender: this.data.userInfo.gender,
          nickName: this.data.userInfo.nickName,
          province: this.data.userInfo.province,
        }
      })
      .then((res) => {
        console.log("添加用户信息成功", res);
      })
      .catch((res) => {
        console.log("添加用户信息失败", res);
      });
  },
  //wx.cloud.database().command.eq()
  getDBInfo(openid) {
    wx.cloud
      .database()
      .collection("userInfo")
      .where({
        openid: openid
      })
      .get()
      .then((res) => {
        console.log("获取消息长度", res.data);
        if (res.data.length == 0) {
          // 如果数据库没有openid信息，添加用户信息
          console.log("请添加用户信息");
          this.addInfo();
        } else {
          console.log("获取用户信息成功", res);
          this.setData({
            openid: res.data[0].openid,
            avatarUrl: res.data[0].avatarUrl,
            city: res.data[0].city,
            country: res.data[0].country,
            gender: res.data[0].gender,
            nickName: res.data[0].nickName,
            province: res.data[0].province,
          });
          let nickName = res.data[0].nickName
          console.log("获取用户昵称成功", nickName);
        }
      })
      .catch((res) => {
        console.log("获取用户信息失败", res);
      });
  },
  //发送模板消息到多个用户,推送之前要先获取用户的openid
  sendAll() {
    wx.cloud
      .database()
      .collection("userInfo")
      .get()
      .then((res) => {
        let userInfo = res.data
        console.log("获取所有用户信息成功", userInfo);
        userInfo.forEach((item) => {
          console.log("推送一个消息成功", item.openid);
          this.sendFun(item.openid);
        });
      })
      .catch((res) => {
        console.log("推送消息失败", res);
      });
  },
  sendFun(openid) {
    wx.cloud
      .callFunction({  // sendMsg
        name: "pushNotify",
        data: {
          openid: openid,
        }
      })
      .then((res) => {
        console.log("推送消息成功", res);
      })
      .catch((res) => {
        console.log("推送消息失败", res);
      });
  },
  /**
* 启动定时器
*/
  startInter: function () {
    var that = this;

    that.data.inter = setInterval(
      function () {
        // TODO 你需要无限循环执行的任务 3600000
        addWeather();
        console.log('setInterval 每过一个小时执行一次天气信息添加入数据库任务')
      }, 7200000);
  },
  /** 
   * 结束定时器
   */
  endInter: function () {
    var that = this;
    that.clearInterval(that.data.inter)
  },
  shouquan() {
    wx.requestSubscribeMessage({
      tmplIds: ["prkk-ISwwp-FuZhoaoPD6PIz80fHCFsLg6L8gtv0ijw"],
      //这里填入我们生成的模板id
      success(res) {
        console.log("授权成功", res);
      },
      fail(res) {
        console.log("授权失败", res);
      },
    });
  },
  //授权提示弹窗
  onShowModal1() {
    wx.showModal({
      title: '获取用户信息',
      content: '为了获得更好的使用体验，需要用户授权个人信息',
      cancelText: "取消",
      cancelColor: "#00f",
      confirmText: "确认",
      confirmColor: "#f00",
      complete: (res) => {
        if (res.cancel) {
          this.onShowToast();
        }
        if (res.confirm) {
          console.log("test1:")
          this.getUserProfile()
        }
      }
    })
    // this.sendAll();
  },
  onShowModal2() {
    wx.showModal({
      title: '订阅消息确认',
      content: '避免错过重要信息，点击确认按钮进行订阅消息(务必勾选总保持以上选择)',
      cancelText: "取消",
      cancelColor: "#00f",
      confirmText: "确认",
      confirmColor: "#f00",
      complete: (res) => {
        if (res.cancel) {
          this.onShowToast();
        }
        if (res.confirm) {
          console.log("test1:")
          this.shouquan(); //调用订阅授权
        }
      }
    })
  },
  onShowToast() {
    wx.showToast({
      title: '授权失败',
      icon: "error",
      duration: 3000,
      mask: true,
      success() {
        console.log("显示成功");
      },
      fail() {
        console.log("显示失败");
      },
      complete() {
        console.log("complete");
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getToday: function () {
    let day = util.formatTime(new Date());
    let theday = day;
    console.log(theday);
    this.setData({
      theDay: theday
    })
  },
  testWeather() {
    wx.cloud
    .callFunction({  // sendMsg
      name: "clockWeather",
    })
    .then((res) => {
      console.log("查询天气成功", res);
    })
    .catch((res) => {
      console.log("查询天气失败", res);
    });
  },
  onLoad: function (options) {
    this.getToday();
    this.onShowModal1();
    setTimeout(() => {
      this.onShowModal2();
    }, 4000)
    setTimeout(() => {
      this.getOpenid();
    }, 6000)
    // this.startInter();
    addLocation();
    // this.testWeather();
    // this.sendFun();
  },
  onShow: function () {

  }
})